package com.qmth.gkwb.api;

import java.util.List;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qmth.gkwb.data.constant.OrderStatus;
import com.qmth.gkwb.data.document.Order;
import com.qmth.gkwb.data.entity.ZFZFMX;
import com.qmth.gkwb.data.exception.OrderCreateFailException;
import com.qmth.gkwb.data.pay.OrderService;
import com.qmth.gkwb.data.repository.OrderRepo;
import com.qmth.gkwb.data.repository.ZFZFMXRepo;

@RestController
@RequestMapping("api/orders")
public class OrderApi {

	@Autowired private OrderService orderService;
	@Autowired private OrderRepo orderRepo;
	@Autowired private ZFZFMXRepo zfmxRepo;
	
	/**
	 * 订单查询
	 * @param examId　报名号
	 * @param status（可选）订单状态
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public List<Order> query(@RequestParam String examId,@RequestParam(required=false) OrderStatus status){
		List<Order> orders = null;
		if(status != null){
			orders = orderRepo.findByExamIdAndStatus(examId, status);
		}
		else{
			orders = orderRepo.findByExamId(examId);
		}
		return orders;
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public Order insert(@RequestBody Order order) throws OrderCreateFailException{
		Order result = orderService.createOrder(order);
		return result;
	}
	
	@RequestMapping(value="zfmx",method=RequestMethod.GET)
	public JSONObject queryZFMX(@RequestParam int page,@RequestParam(required=false) Integer size,
			@RequestParam(required=false) String examId){
		JSONObject result = new JSONObject();
		List<ZFZFMX> orders = null;
		size = size == null?10:size;
		if(examId == null){
			Page<ZFZFMX> list = zfmxRepo.findAll(new PageRequest(page, size));
			long count = zfmxRepo.count();
			orders = list.getContent();;
			result.accumulate("list", orders);
			result.accumulate("count",count);
		}
		else{
			orders = zfmxRepo.findByExamId(examId, new PageRequest(page, size));
			long count = zfmxRepo.countByExamId(examId);
			result.accumulate("list", orders);
			result.accumulate("count",count);
		}
		return result;
	}
}
